<?php
namespace frontend\modules\v1\controllers;


use common\logic\SendRedpacketLogic;
use common\logic\PayRedpacketCallBack;
use common\models\SendRedpacketModel;
use common\models\UserModel;
use common\models\GetRedpacketModel;
use frontend\common\ApiController;
use common\wx\JsApiPay;
use common\wx\WxPayApi;
use common\wx\WxPayUnifiedOrder;
use common\wx\WxTransfers;
use common\wx\WxTransfersConfig;

//红包功能
class RedpacketController extends ApiController
{
	//添加红包
	public function actionAddRedpacket()
    {
    	//userid
    	//total 红包金额
    	//nums 红包数量
    	$uid = \Yii::$app->request->post('uid', 0);
    	$total = \Yii::$app->request->post('total', 0);
    	$nums = \Yii::$app->request->post('nums', 0);
    	$msgs = \Yii::$app->request->post('msgs', '');
    	//添加方法
        $addArr = SendRedpacketLogic::instance()->AddRedPacket($uid,$total,$nums,$msgs);
        if($addArr['error']!='ok'){
        	return $this->error($addArr['error']);
        }
        
    	
    	//进入支付页面
    	$tools = new JsApiPay();
        //②、统一下单
        $input = new WxPayUnifiedOrder();
        $input->SetBody('红包');
        $input->SetOut_trade_no($addArr['order_sn']);
        $input->SetTotal_fee($addArr['total'] * 100);
        $input->SetTime_start(date("YmdHis"));
//        $input->SetNotify_url(FRONTEND_URL."/v1/redpacket/call-back");
        $input->SetNotify_url(FRONTEND_URL . "/v1/coupon/red-back");
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($addArr['openid']);
        $order = WxPayApi::unifiedOrder($input);
        $jsApiParameters = $tools->GetJsApiParameters($order);

		$orders = ['rid'=>$addArr['order_sn'],'total'=>$addArr['total']];
        //获取共享收货地址js函数参数
        return $this->success(['order' => $orders, 'jsApiParameters' => $jsApiParameters,'backurl='=>FRONTEND_URL."/v1/redpacket/call-back"]);
            
    }
    
    public function actionCallBack()
    {
    	$db = \Yii::$app->db;	
		$getuser = $db->createCommand("insert into ph_errorlog(msg)values('im back ccc222')")->execute();
		
        $notify = new PayRedpacketCallBack();
        $notify->testaaa();
        
        $notify->Handle(false);
        exit;
    }
    
    //领取红包
    public function actionGetRedpacket(){
    	//1.uid  用户id
    	//2.rid  红包id 用红包的 order_sn
    	
    	//1.判断用户是否新注册的
    	//2.判断红包订单是否支付
    	//3.判断红包数量是否领取完
    	
    	//修改用户余额
    	//修改红包数量
    	//添加红包领取记录
    	
    	$uid = \Yii::$app->request->post('uid', 0);
    	$rid = \Yii::$app->request->post('rid', '');
    	
    	$user = UserModel::findOne(['id' => $uid]);
        if (empty($user)) {
        	return $this->error('用户不存在');
        }
        
        if($user->isgetredpacket==1){
        	return $this->error('你已经领取过红包了哦！');
        }
        
        $order = SendRedpacketModel::findOne(['order_sn' => $rid]);
        if(empty($order)){
            return $this->error('订单不存在');
        }
        
        if($order->paystate != 1){
        	return $this->error('无效的红包');
        }
        
        if($order->curnums >= $order->nums){
        	return $this->error('红包已经被领取完了');
        }
        
        //判断以前是否领取过这个红包
        $meget = GetRedpacketModel::findOne(['redid' => $order->rid,'userid'=>$uid]);
        if (!empty($meget)) {
        	return $this->error('你已经领取过这个红包了');
        }
        
        $getmoney = 0;
        $lastredpacket = $order->nums - $order->curnums;
        $curmoney = $order->curmoney;
        if($lastredpacket == 1){
        	$getmoney = $curmoney;
        }
        else{
        	$getmoney = $curmoney - sprintf("%.2f",$curmoney*(rand(65,80)/100));
        	$getmoney = $getmoney<0.01?0.01:$getmoney;
        }
        
        
        $getmodel = new GetRedpacketModel();
        
        $db = \Yii::$app->db;
		$transaction = $db->beginTransaction();
		try {		    
		    $order->curnums += 1;
		    $order->curmoney = $order->curmoney -$getmoney;
		    if(!$order->save()){
		    	throw new \Exception('订单修改失败！');
		    }
		    
		    
		    $getmodel->getsum = $getmoney;
		    $getmodel->redid = $order->rid;
		    $getmodel->userid = $user->id;
		    $getmodel->gettime = time();
		    $getmodel->state = 0;
		    
		    
		    if(!$getmodel->save()){
		    	throw new \Exception('红包订单添加失败！');
		    }
		    
		    $transaction->commit();
		} catch(\Exception $e) {
		    $transaction->rollBack();
		    return $this->error($e->getMessage());
		}
        return $this->success(['getmoney'=>$getmoney,'srid'=>$getmodel->gid]);
    }
    
    //分享后领取红包
    public function actionShareGet(){
    	//用户编号
    	$uid = \Yii::$app->request->post('uid', 0);
    	//领取红包编号
    	$srid = \Yii::$app->request->post('srid', '');
    	
    	$getorder = GetRedpacketModel::findOne(['gid' => $srid]);
        if(empty($getorder)){
            return $this->error('订单不存在');
        }
        
        if($getorder['state'] == 1){
        	return $this->error('红包已经领取过了');
        }
        
        if($getorder['userid'] != $uid){
        	return $this->error('用户信息错误');
        }
        
        $user = UserModel::findOne(['id' => $uid]);
        if (empty($user)) {
        	return $this->error('用户不存在');
        }
        $getmoney = 0;
        //领取余额
        $db = \Yii::$app->db;
		$transaction = $db->beginTransaction();
		try {		    
		    //用户获得红包余额
		    $getmoney = $getorder->getsum;
		    $user->isgetredpacket = 1;
		    $user->redpacket_money += $getmoney;
		    $user->redpacket_num += 1;
		    if(!$user->save()){
		    	throw new \Exception('用户信息修改失败！');
		    }
		    
		    //领取订单修改
		    $getorder->state = 1;
		    if(!$getorder->save()){
		    	throw new \Exception('红包订单添加失败！');
		    }
		    
		    $transaction->commit();
		} catch(\Exception $e) {
		    $transaction->rollBack();
		    return $this->error($e->getMessage());
		}
        
        return $this->success(['redpacket_money'=>$user->redpacket_money,'redpacket_num'=>$user->redpacket_num]);
    }
    
    //分享红包详情
    public function actionShareMsg(){
    	//$rid 红包编号
    	$rid = \Yii::$app->request->post('rid', '');
    	$uid = \Yii::$app->request->post('uid', 0);
    	
    	
    	
    	$order = SendRedpacketModel::findOne(['order_sn' => $rid]);
        if(empty($order)){
            return $this->error('订单不存在');
        }

    	$redid = $order['rid'];   	
    	$sqlstr = "select count(redid) from ph_get_redpacket where redid=$redid";
    	$db = \Yii::$app->db;	
		$query = $db->createCommand($sqlstr)->queryAll();
		
		$getnum = 0;
		if(count($query)>0){
			$getnum = $query[0]['count(redid)'];
		}
    	
    	
    	$sqlstr = "SELECT a.*, b.nickname, b.avatar FROM ph_get_redpacket a 
			LEFT JOIN ph_user b ON a.userid=b.id WHERE a.redid=$redid LIMIT 5";
    	$db = \Yii::$app->db;	
		$getuser = $db->createCommand($sqlstr)->queryAll();
    	
    	$total = 0;
    	if($uid>0){
	    	$getOrder = GetRedpacketModel::findOne(['userid'=>$uid,'redid'=>$redid,'state'=>1]);
	    	if($getOrder){
	    		$total = $getOrder['getsum'];
	    	}
    	}
//  	$getuser = GetRedpacketModel::find()->select("a.*,b.nickname,b.avatar")->alias('a')->
//  	leftJoin('ph_user b','a.userid=b.id')->where(['a.redid'=>$redid])->limit(5)->all();
        
        return $this->success(['all'=>$getnum,'user'=>$getuser,'total'=>$total]); 
    }
    
    
    public function actionMeList(){
    	//用户编号
    	$uid = \Yii::$app->request->post('uid', 0);
    	
    	$sqlstr = "SELECT * from ph_send_redpacket where userid = $uid and paystate = 1 order by rid desc";
    	$db = \Yii::$app->db;	
		$list = $db->createCommand($sqlstr)->queryAll();
		
    	return $this->success(['all'=>$list]);
    }
    
    public function actionMeMoney(){
    	//用户编号
    	$uid = \Yii::$app->request->post('uid', 0);
    	$user = UserModel::findOne(['id' => $uid]);
        if (empty($user)) {
        	return $this->error('用户不存在');
        }
		
    	return $this->success(['memoney'=>$user['redpacket_money']]);
    }
    
    //提现
    public function actionWithdraw(){
    	//uid
    	//nums
    	
    	//判断用户是否存在
    	//判断余额是否充足
    	
    	$uid = \Yii::$app->request->post('uid', 0);
    	$nums = \Yii::$app->request->post('nums', 0);
    	$minmoney = 10;
    	$maxmoney = 200;
    	$user = UserModel::findOne(['id' => $uid]);
        if (empty($user)) {
        	return $this->error('用户不存在');
        }
        
        $redpacket_money = $user->redpacket_money;
        
        if($nums<$minmoney){
        	return $this->error('单次提现额最少'.$minmoney.'元');
        }
        
        if($nums>$maxmoney){
        	return $this->error('单次提现额最多'.$maxmoney.'元');
        }
        
        if($redpacket_money<$nums){
        	return $this->error('你的余额不足');
        }
        
        $openid = $user['openid'];
        //开始提现操作
        $data=array(
			'openid'=>$openid,//openid
			'check_name'=>'NO_CHECK',//是否验证真实姓名参数
			're_user_name'=>$user['nickname'],//姓名
			'amount'=>$nums*100,//最小1元 也就是100
			'desc'=>"口袋买房提现通知"//描述
		);
		
		$backmsg = transfer($data);
		if($backmsg == 'SUCCESS'){
//			returnMoneyUser($order);
			//修改用户余额
    		//添加提现记录
    		$db = Yii::$app->db;
			$transaction = $db->beginTransaction();
			try {		    
			    $user->redpacket_money = $user->redpacket_money - $nums;			
	    		if(!$user->save()){
	    			throw new \Exception('用户信息修改失败！');
	    		}
	    		
	    		$wmodel = new WithdrawModel();
    			$wmodel->userid = $user->id;
    			$wmodel->money = $nums;
    			$wmodel->times = time();    			
    			if(!$wmodel->save()){
    				throw new \Exception('提现订单添加失败！');
    			}
	    		
			    $transaction->commit();
			} catch(\Exception $e) {
			    $transaction->rollBack();
			    return $this->error($e->getMessage());
			}
    		
			$this->success(['memoney'=>$user->redpacket_money]);
		}
		else{
			$this->error('领取失败');
		}
    }
    
    // 微信提现批量转账
    function transfer($data){
    	
//  	echo('退款吧！');
		$path = WxTransfersConfig::getRealPath(); // 证书文件路径
		$config['wxappid'] = WxTransfersConfig::APPID;
		$config['mch_id'] = WxTransfersConfig::MCHID;
		$config['key'] = WxTransfersConfig::KEY;
		$config['PARTNERKEY'] = WxTransfersConfig::KEY;
		$config['api_cert'] = $path . WxTransfersConfig::SSLCERT_PATH;
		$config['api_key'] = $path . WxTransfersConfig::SSLKEY_PATH;
		$config['rootca'] = $path . WxTransfersConfig::SSLROOTCA;
//		
		$wxtran=new WxTransfers($config);
//		
		//$wxtran->setLogFile(dirname(dirname(__FILE__))."/weixin/transferslog/transfers.txt");//日志地址
//		
		$data['spbill_create_ip']=$wxtran->getServerIp();//服务器IP地址
		$backState = $wxtran->transfers($data);
		if($backState == true){
			return "SUCCESS";
		}
		else{
			$wxtran->log('fail',$wxtran->error);
			return $wxtran->error;
		}
		
    }
}
?>